<template>
  <a-drawer
    :title="title"
    :width="720"
    :visible="visible"
    :wrapStyle="{height: '100%',overflow: 'auto',paddingBottom: '108px'}"
    @close="onClose"
  >

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="用户账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input
            placeholder="请输入用户账号"
            v-decorator="['username',{ rules: [
              { required: true, message: '请输入用户账号!' }
            ] }]"
            :readOnly="!!model.id"
          />
        </a-form-item>

        <template v-if="!model.id">
          <a-form-item label="登陆密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
            <a-input
              autoComplete="new-password"
              type="password"
              placeholder="请输入登陆密码"
              v-decorator="['password',{ rules: [
                { required: true, pattern: passwordPattern, message: '密码由8位数字、大小写字母和特殊符号组成!' },
                { validator: validateToNextPassword }
              ] }]"
            />
          </a-form-item>

          <a-form-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
            <a-input
              type="password"
              @blur="handleConfirmBlur"
              placeholder="请重新输入登陆密码"
              v-decorator="['confirmpassword',{ rules: [
                { required: true, message: '请重新输入登陆密码!' },
                { validator: compareToFirstPassword }
              ] }]"
            />
          </a-form-item>
        </template>

        <a-form-item label="用户姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-input
            placeholder="请输入用户姓名"
            v-decorator="['realname',{rules: [{ required: true, message: '请输入用户姓名!' }]}]"
          />
        </a-form-item>

        <a-form-item label="工号" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入工号" v-decorator="['workNo', {rules: [{ required: true, message: '请输入工号!' }]}]" />
        </a-form-item>

        <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select v-decorator="[ 'sex', {}]" placeholder="请选择性别">
            <a-select-option :value="1">男</a-select-option>
            <a-select-option :value="2">女</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="角色分配" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-select
            mode="multiple"
            style="width: 100%"
            placeholder="请选择用户角色"
            optionFilterProp="children"
            v-decorator="['selectedRole']"
          >
            <a-select-option v-for="(role,roleindex) in roleList" :key="roleindex.toString()" :value="role.id">
              {{ role.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="部门分配" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <tree-select
            style="width: 100%"
            :treeData="departTree"
            treeCheckable
            placeholder="请选择部门"
            allowClear
            multiple
            treeDefaultExpandAll
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            v-decorator="['selecteddeparts']"
          />
        </a-form-item>

        <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入邮箱" v-decorator="[ 'email', {rules: [{type: 'email', message: '请输入正确的邮箱！'},{ required: true, message: '请输入邮箱!' }]}]" />
        </a-form-item>

        <a-form-item label="手机号码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入手机号码" v-decorator="[ 'phone', {rules: [{validator: validatePhone}]}]" />
        </a-form-item>
      </a-form>
    </a-spin>
    <div class="drawer-bottom-button">
      <a-button :style="{marginRight: '8px'}" @click="onClose">取消</a-button>
      <a-button @click="handleSubmit" type="primary">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { TreeSelect } from 'ant-design-vue'
import pick from 'lodash.pick'
import { apiQueryDepartIdTree, apiQueryAllRole, apiQueryUserRole, apiQueryUserDepartList, apiAddUser, apiEditUser } from '@/api/system'

export default {
  name: 'UserModal',
  components: {
    TreeSelect
  },
  data () {
    return {
      visible: false,
      model: {},
      roleList: [],
      selectedRole: [],
      checkedDepartNameString: '',
      checkedDepartKeys: [],
      identity: '1',
      departTree: [],
      userDepartModel: { userId: '', departIdList: [] },
      userId: '',
      form: this.$form.createForm(this),
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      disableSubmit: false,
      title: '',
      passwordPattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
      confirmDirty: false,
      dateFormat: 'YYYY-MM-DD'
    }
  },
  mounted () {
    // 角色列表
    this.initialRoleList()
    // 部门树
    this.initialDepartTree()
  },
  methods: {
    initialRoleList () {
      apiQueryAllRole().then((res) => {
        this.roleList = res.result
      })
    },
    initialDepartTree () {
      apiQueryDepartIdTree().then((res) => {
        this.departTree = res.result
      })
    },
    initalData () {
      this.checkedDepartKeys = []
      this.checkedDepartNameString = ''
      this.userId = null
      this.model = {}
    },
    loadUserRoles (userid) {
      const that = this
      apiQueryUserRole({ userid: userid }).then((res) => {
        if (res.result) {
          // this.selectedRole = res.result
          that.form.setFieldsValue({ selectedRole: res.result })
        } else {
          console.log(res.message)
        }
      })
    },
    loadUserDepart (userid) {
      const that = this
      apiQueryUserDepartList({ userId: userid }).then((res) => {
        if (res.result) {
          const selecteddeparts = []
          res.result.forEach(item => {
            selecteddeparts.push(item.value)
          })
          that.form.setFieldsValue({ selecteddeparts: selecteddeparts })
        }
      })
    },
    show (title, record) {
      this.visible = true
      this.title = title
      if (record) {
        this.defaultFormData(record)
      } else {
        this.initalData()
        this.$nextTick(() => {
          this.form.resetFields()
        })
      }
    },
    defaultFormData (record) {
      const that = this
      that.checkedDepartNameString = ''
      that.userId = record.id
      that.form.resetFields()
      that.model = Object.assign({}, record)
      that.loadUserRoles(that.userId)
      that.loadUserDepart(that.userId)
      that.$nextTick(() => {
        that.form.setFieldsValue(pick(this.model, 'username', 'sex', 'realname', 'email', 'phone', 'workNo'))
      })
    },
    onClose () {
      this.visible = false
    },
    validateToNextPassword  (rule, value, callback) {
      const form = this.form
      const confirmpassword = form.getFieldValue('confirmpassword')
      if (value && confirmpassword && value !== confirmpassword) {
        // eslint-disable-next-line standard/no-callback-literal
        callback('两次输入的密码不一样！')
      }
      if (value && this.confirmDirty) {
        form.validateFields(['confirm'], { force: true })
      }
      callback()
    },
    compareToFirstPassword  (rule, value, callback) {
      const form = this.form
      if (value && value !== form.getFieldValue('password')) {
        // eslint-disable-next-line
        callback('两次输入的密码不一样！')
      } else {
        callback()
      }
    },
    handleConfirmBlur  (e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    validatePhone (rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (!new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
          // eslint-disable-next-line
          callback('请输入正确格式的手机号码!')
        }
      }
    },
    handleSubmit () {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        console.log(err)
        if (!err) {
          console.log(values)
          that.confirmLoading = true
          const formData = Object.assign(this.model, values)
          formData.selecteddeparts = values.selecteddeparts && values.selecteddeparts.length > 0 ? values.selecteddeparts.join(',') : ''
          formData.selectedroles = values.selectedRole && values.selectedRole.length > 0 ? values.selectedRole.join(',') : ''
          let obj
          if (!this.model.id) {
            // formData.id = this.userId
            obj = apiAddUser(formData)
          } else {
            obj = apiEditUser(formData)
          }
          obj.then((res) => {
            if (res.success) {
              that.$emit('ok')
              that.onClose()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    }

  }
}
</script>

<style scoped>
.drawer-bottom-button {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
}
</style>
